{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "88149428",
   "metadata": {},
   "source": [
    "# 语音识别（实践）\n",
    "\n",
    "* 语音-->文本（ASR：Automatic Speech Recognition）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ea43ec35",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.5de27b52f0b99630529b3314e53e6f5f.315360000.1999133490.282335-33415623\",\"expires_in\":2592000,\"session_key\":\"9mzdDtAHmxoYDgr5mR9rGTWrU9eR7fnWYCiIvchH2Ce2sAEqamvC4yTpoYtt1kDmjZ7lr4f5himyJS4bPNQ1xDV\\/MF2Brg==\",\"access_token\":\"24.5b916619d808034068c240a79eb85585.2592000.1686365490.282335-33415623\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"4800b31362fa64e48b7c61450300aec3\"}\n",
      "\n",
      "{'refresh_token': '25.5de27b52f0b99630529b3314e53e6f5f.315360000.1999133490.282335-33415623', 'expires_in': 2592000, 'session_key': '9mzdDtAHmxoYDgr5mR9rGTWrU9eR7fnWYCiIvchH2Ce2sAEqamvC4yTpoYtt1kDmjZ7lr4f5himyJS4bPNQ1xDV/MF2Brg==', 'access_token': '24.5b916619d808034068c240a79eb85585.2592000.1686365490.282335-33415623', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '4800b31362fa64e48b7c61450300aec3'}\n",
      "audio_voice_assistant_get\n",
      "SUCCESS WITH TOKEN: 24.5b916619d808034068c240a79eb85585.2592000.1686365490.282335-33415623  EXPIRES IN SECONDS: 2592000\n",
      "Request time cost 0.766968\n",
      "{\"corpus_no\":\"7231752074123006192\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"83842074431683773490\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import base64\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = 'GSeghDdXyoZAGD2PgfiEBTT2'\n",
    "SECRET_KEY = 'sKUfYH2vDovc4TVGrmWRBL3qDvuNj23Y'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = 'speech-demo-master/rest-api-asr/python/audio/16k.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:]  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON'\n",
    "# 采样率\n",
    "RATE = 16000  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "# DEV_PID = 80001\n",
    "# ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "# SCOPE = 'brain_enhanced_asr'  # 有此scope表示有极速版能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode( 'utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str =  result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        print(SCOPE)\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s  EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    speech = base64.b64encode(speech_data)\n",
    "    if (IS_PY3):\n",
    "        speech = str(speech, 'utf-8')\n",
    "    params = {'dev_pid': DEV_PID,\n",
    "             #\"lm_id\" : LM_ID,    #测试自训练平台开启此项\n",
    "              'format': FORMAT,\n",
    "              'rate': RATE,\n",
    "              'token': token,\n",
    "              'cuid': CUID,\n",
    "              'channel': 1,\n",
    "              'speech': speech,\n",
    "              'len': length\n",
    "              }\n",
    "    post_data = json.dumps(params, sort_keys=False)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL, post_data.encode('utf-8'))\n",
    "    req.add_header('Content-Type', 'application/json')\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print (\"Request time cost %f\" % (timer() - begin))\n",
    "    except URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\",\"w\") as of:\n",
    "        of.write(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7372abb9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7231752074123006192\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"83842074431683773490\"}\\n'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result_str"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8190822",
   "metadata": {},
   "source": [
    "# 假设我们自己就是自动回复的机器人\n",
    "\n",
    "* 创建回复字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f101ec35",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好\":\"好呀好呀\",\n",
    "    \"北京科技馆。\":\"中国科技馆是我国唯一的国家级综合性科技馆，是实施科教兴国战略、人才强国战略和创新驱动发展战略， 提高全民科学素质的大型科普基础设施。\"\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db88fcb6",
   "metadata": {},
   "source": [
    "* 如果字符串里面是字典，我们可以用eval：str-->dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "04a159ce",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'北京科技馆。'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result_整理 = eval(result_str)['result'][0]\n",
    "result_整理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5108f54a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'中国科技馆是我国唯一的国家级综合性科技馆，是实施科教兴国战略、人才强国战略和创新驱动发展战略， 提高全民科学素质的大型科普基础设施。'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get(result_整理)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "890d6b34",
   "metadata": {},
   "source": [
    "# 语音合成\n",
    "\n",
    "* 文本-->语音（TTS：TextToSpeech）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "48f75d1a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fetch token begin\n",
      "{\"refresh_token\":\"25.3a0df0165be3fdb039bc50647def2ef1.315360000.1999136001.282335-33415623\",\"expires_in\":2592000,\"session_key\":\"9mzdDxemSfNZpPaq2RramUIke01t1LKZGTprzLnQfrL8NrR5P9dmXvc5p42FXb6\\/wZEnUGw6nx8uFPtxuQGA88n6UNoAsw==\",\"access_token\":\"24.438bbd2fa02bf26e9fd67e87747f814b.2592000.1686368001.282335-33415623\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"40dd24a4359424ccf646c58c942aee4b\"}\n",
      "\n",
      "{'refresh_token': '25.3a0df0165be3fdb039bc50647def2ef1.315360000.1999136001.282335-33415623', 'expires_in': 2592000, 'session_key': '9mzdDxemSfNZpPaq2RramUIke01t1LKZGTprzLnQfrL8NrR5P9dmXvc5p42FXb6/wZEnUGw6nx8uFPtxuQGA88n6UNoAsw==', 'access_token': '24.438bbd2fa02bf26e9fd67e87747f814b.2592000.1686368001.282335-33415623', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '40dd24a4359424ccf646c58c942aee4b'}\n",
      "SUCCESS WITH TOKEN: 24.438bbd2fa02bf26e9fd67e87747f814b.2592000.1686368001.282335-33415623 ; EXPIRES IN SECONDS: 2592000\n",
      "%E4%B8%AD%E5%9B%BD%E7%A7%91%E6%8A%80%E9%A6%86%E6%98%AF%E6%88%91%E5%9B%BD%E5%94%AF%E4%B8%80%E7%9A%84%E5%9B%BD%E5%AE%B6%E7%BA%A7%E7%BB%BC%E5%90%88%E6%80%A7%E7%A7%91%E6%8A%80%E9%A6%86%EF%BC%8C%E6%98%AF%E5%AE%9E%E6%96%BD%E7%A7%91%E6%95%99%E5%85%B4%E5%9B%BD%E6%88%98%E7%95%A5%E3%80%81%E4%BA%BA%E6%89%8D%E5%BC%BA%E5%9B%BD%E6%88%98%E7%95%A5%E5%92%8C%E5%88%9B%E6%96%B0%E9%A9%B1%E5%8A%A8%E5%8F%91%E5%B1%95%E6%88%98%E7%95%A5%EF%BC%8C+%E6%8F%90%E9%AB%98%E5%85%A8%E6%B0%91%E7%A7%91%E5%AD%A6%E7%B4%A0%E8%B4%A8%E7%9A%84%E5%A4%A7%E5%9E%8B%E7%A7%91%E6%99%AE%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD%E3%80%82\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.438bbd2fa02bf26e9fd67e87747f814b.2592000.1686368001.282335-33415623&tex=%25E4%25B8%25AD%25E5%259B%25BD%25E7%25A7%2591%25E6%258A%2580%25E9%25A6%2586%25E6%2598%25AF%25E6%2588%2591%25E5%259B%25BD%25E5%2594%25AF%25E4%25B8%2580%25E7%259A%2584%25E5%259B%25BD%25E5%25AE%25B6%25E7%25BA%25A7%25E7%25BB%25BC%25E5%2590%2588%25E6%2580%25A7%25E7%25A7%2591%25E6%258A%2580%25E9%25A6%2586%25EF%25BC%258C%25E6%2598%25AF%25E5%25AE%259E%25E6%2596%25BD%25E7%25A7%2591%25E6%2595%2599%25E5%2585%25B4%25E5%259B%25BD%25E6%2588%2598%25E7%2595%25A5%25E3%2580%2581%25E4%25BA%25BA%25E6%2589%258D%25E5%25BC%25BA%25E5%259B%25BD%25E6%2588%2598%25E7%2595%25A5%25E5%2592%258C%25E5%2588%259B%25E6%2596%25B0%25E9%25A9%25B1%25E5%258A%25A8%25E5%258F%2591%25E5%25B1%2595%25E6%2588%2598%25E7%2595%25A5%25EF%25BC%258C%2B%25E6%258F%2590%25E9%25AB%2598%25E5%2585%25A8%25E6%25B0%2591%25E7%25A7%2591%25E5%25AD%25A6%25E7%25B4%25A0%25E8%25B4%25A8%25E7%259A%2584%25E5%25A4%25A7%25E5%259E%258B%25E7%25A7%2591%25E6%2599%25AE%25E5%259F%25BA%25E7%25A1%2580%25E8%25AE%25BE%25E6%2596%25BD%25E3%2580%2582&per=4&spd=5&pit=5&vol=5&aue=3&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "result saved as :result.mp3\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "\n",
    "\n",
    "TEXT = qa.get(result_整理)\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 4\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 5\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 5\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 3\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    print(\"fetch token begin\")\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not SCOPE in result['scope'].split(' '):\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73e91b2c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3db3faf3",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5867b4be",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46dd000e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
